import { Router } from '@angular/router';
import { CommonServiceSvr } from './../../service/common.service';
import { Component } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { CustomerServiceSvr } from '../../service/register.service'
import { MyValidationErrors, MyValidators } from 'src/app/service/myValidators.service';
import { NzMessageService } from 'ng-zorro-antd/message';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.less']
})



export class RegisterComponent {

  constructor(private fb: FormBuilder,
    public customer: CustomerServiceSvr, private message: NzMessageService,
    private common: CommonServiceSvr, public router: Router
    ) {
    // 引入表单校验条件
    const { required, maxLength, minLength, email, phone, password } = MyValidators;

    // 表单校验
    this.validateForm = this.fb.group({
      nickname: ['', [required, maxLength(12), minLength(5)]], // 昵称
      phone: ['', [required, phone]], // 手机号
      email: ['', [required, email]], // 邮箱
      password: ['', [required, maxLength(16), minLength(8)]], // 密码
      confirmPassword: ['', [this.confirmPasswordValidator]], // 确认密码
      sex: [0, [required]], // 性别
      birthday: ['', [required]], // 出生日期
      code: ['', [required]], //验证码
      address: ['', [required]] // 住址
    });
  }

   // 注册表单
   validateForm: FormGroup;
   codeFlag: number = 0;
   codeData: string = '';
    //  请求返回的结果
    res: String | undefined;
    // 验证码倒计时
    codeCount: number = 0;
    timer: any = null;
    showCodeBtn = true



  // 格式自动提示
  autoTips: Record<string, Record<string, string>> = {
    'zh-cn': {
      required: '必填项'
    },
    default: {
      email: '邮箱格式不正确'
    }
  };

  // 确认密码校验
  validateConfirmPassword(): void {
    setTimeout(() => this.validateForm.controls['confirmPassword'].updateValueAndValidity());
  }

  // 判断确认密码是否和密码相同
  confirmPasswordValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { error: true, required: true };
    } else if (control.value !== this.validateForm.controls['password'].value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  // 获取验证码
  async getCaptcha(): Promise<boolean> {
    const Time: number = 60
    if(this.timer !== -1) {
      this.codeCount = Time
      this.showCodeBtn = false
      this.timer = setInterval(()=>{
        if(this.codeCount>0 && this.codeCount <= Time) {
          this.codeCount--
        } else {
          this.showCodeBtn = true
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)

    }
    const arr = Object.values(this.validateForm.controls)
    if(arr[1].valid) {
      // 手机号有效或都有效
      this.codeFlag = 1
      this.codeData = this.validateForm.value.phone
    } else if (arr[2].valid) {
      // 邮箱有效
      this.codeFlag = 2
      this.codeData = this.validateForm.value.email
    } else {
      // 都无效
      this.message.error('请输入正确的邮箱或手机号码');
      return false
    }

    const res = await this.common.sendCode(this.codeData, this.codeFlag)
    if(res !== undefined) {
      this.message.error('验证码获取失败')
    }

    return true
  }

  // 提交表单
  async submitForm(): Promise<void> {
    if (this.validateForm.valid) {
      try {
        const res = await this.customer.saveCustomer(this.validateForm.value.phone, this.validateForm.value.code,
          this.validateForm.value.password, this.validateForm.value.confirmPassword,
          this.validateForm.value.nickname, this.validateForm.value.sex,
          Number(new Date(this.validateForm.value.birthday)), this.validateForm.value.email, this.validateForm.value.address, '')
          if(res === 1) {
            this.message.success('新用户注册成功')
            this.showCodeBtn = true
            clearInterval(this.timer)
            this.timer = null
            this.router.navigate(['/login'])
          }
      } catch (error) {
        console.log(error)
        this.message.error('注册失败，请重新注册')
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 取消注册
  cancel() {
    this.router.navigate(['/home'])
  }

}
